<template>
    <div 
        class="popover-wrapper" 
        ref="wrapperRef" 
        v-if="props.visible"
        @mousedown.stop
    >
        <div 
            class="popover-content"
            ref="popoverContentRef"
            :style="{ width: width + 'px', top: adjustedTop+'px', left: adjustedLeft+'px' }"
        >
            <div>--{{ pois }}--</div>
            <div>454545454545456454545</div>
            <div>454545454545456454545</div>

            <slot></slot>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick, defineExpose } from '@vue/composition-api'

const props = defineProps({
    pois: Object,
    visible: Boolean,
    width: {
        type: Number,
        default: 200
    },
})

const emit = defineEmits(['update:visible'])

const wrapperRef = ref(null)
const popoverContentRef = ref(null)
const contentHeight = ref(0)

// 计算调整后的位置
const adjustedTop = computed(() => {
    return props.pois.y - (contentHeight.value + 10)
})

const adjustedLeft = computed(() => {
    return props.pois.x - (props.width / 2)
})

// 处理点击外部事件
const handleClickOutside = (event) => {
    console.log("handleClickOutside1=1=", props.visible)
    if (!props.visible) return
    const target = event.target
    const wrapper = wrapperRef.value
    console.log("handleClickOutside2=2=", wrapper, target)
    
    if (wrapper && !wrapper.contains(target)) {
        emit('update:visible', false)
    }
}

// 监听内容变化，更新高度
watch(() => props.visible, async (newVal) => {
    if (newVal) {
        await nextTick()
        if (popoverContentRef.value) {
            contentHeight.value = popoverContentRef.value.offsetHeight
        }
    }
})

// 组件挂载后获取内容高度和添加点击事件监听
onMounted(async () => {
    if (props.visible) {
        await nextTick()
        if (popoverContentRef.value) {
            contentHeight.value = popoverContentRef.value.offsetHeight
        }
    }
    // 使用 mousedown 事件而不是 click 事件
    document.addEventListener('mousedown', handleClickOutside)
})

// 组件卸载前移除事件监听
onBeforeUnmount(() => {
    document.removeEventListener('mousedown', handleClickOutside)
})

defineExpose({
    updateContentHeight: async () => {
        await nextTick()
        if (popoverContentRef.value) {
            contentHeight.value = popoverContentRef.value.offsetHeight
        }
    }
})
</script>

<style scoped>
.popover-content {
    position: fixed;
    z-index: 999999;
    padding: 10px;
    border-radius: 10px;
    background-color: #f5f5f5;
    border: 1px solid #000;
}
</style>